//
//  TowerObject.m
//  TowerDefence
//
//  Created by K3 on 5/29/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "TowerObject.h"
#import "PlayScreen.h"

@implementation TowerObject

@synthesize range, maxRadiusFireTarget, buyPrice;

-(id)initTowerObjectWith:(GameLayer *)_gameLayer {
    self = [super initGameObjectWith:_gameLayer];
    spriteBody = [[CCSprite alloc]init];
    isShowOptionMenu = NO;
    isShooting = NO;
    range=[CCSprite spriteWithFile:@"Images/PlayScreen/Range.png"];
    [spriteBody addChild:range];
    range.scale=0;
    buyPrice = 0;
    [self initOptionMenu];
    return self;
}

/*
-(NSMutableArray*)loadAnimationWithNumberOfFrames:(int) numberOfFrames withFrameName:(NSString*)frame{
    NSMutableArray *anim = [[NSMutableArray alloc]init];
    for (int i = 0 ; i < numberOfFrames ; i++)
    {
        NSString *frameName = [[NSString alloc]init];
        frameName = [NSString stringWithFormat:@"%@%d.png",frame,i];
        CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:frameName];
        [anim addObject:frame];
    }
    return anim;
}*/

-(void)initOptionMenu {
    //add four tower into towerMenuTable
    optionMenu = [CCSprite node];
    
    CCSprite *upgradeMenuSprite = [CCSprite spriteWithFile:IMAGE_UPGRADE_TOWER_ICON];

    CCSprite *upgradeTowerLabelSprite = [CCSprite spriteWithFile:IMAGE_MINI_INFO_TABLE];
    upgradeTowerLabelSprite.position = ccp(upgradeMenuSprite.contentSize.width/2, 0);
    CCLabelTTF *upgradeTowerLabel = [CCLabelTTF labelWithString:@"UP" fontName:FONT_COMIC_BOOK fontSize:8];
    upgradeTowerLabel.position = ccp(upgradeTowerLabelSprite.contentSize.width/2, upgradeTowerLabelSprite.contentSize.height/2);
    upgradeTowerLabel.color = ccc3(255, 254, 64);
    [upgradeTowerLabelSprite addChild:upgradeTowerLabel];
    [upgradeMenuSprite addChild:upgradeTowerLabelSprite];
    
    CCMenuItemSprite *upgradeMenuItemSprite = [CCMenuItemSprite itemFromNormalSprite:upgradeMenuSprite selectedSprite:nil target:self selector:@selector(upgradeTowerAnimation)];
    CCMenu *upgradeTowerMenu = [CCMenu menuWithItems:upgradeMenuItemSprite, nil];
    upgradeTowerMenu.position = ccp(50, 50);
    
    CCSprite *sellTowerMenuSprite = [CCSprite spriteWithFile:IMAGE_SELL_TOWER_ICON];
    
    CCSprite *sellTowerLabelSprite = [CCSprite spriteWithFile:IMAGE_MINI_INFO_TABLE];
    sellTowerLabelSprite.position = ccp(sellTowerMenuSprite.contentSize.width/2, 0);
    CCLabelTTF *sellTowerLabel = [CCLabelTTF labelWithString:@"SELL" fontName:FONT_COMIC_BOOK fontSize:10];
    sellTowerLabel.position = ccp(sellTowerLabelSprite.contentSize.width/2, sellTowerLabelSprite.contentSize.height/2);
    sellTowerLabel.color = ccc3(255, 254, 64);
    [sellTowerLabelSprite addChild:sellTowerLabel];
    [sellTowerMenuSprite addChild:sellTowerLabelSprite];
    
    CCMenuItemSprite *sellTowerMenuItemSprite = [CCMenuItemSprite itemFromNormalSprite:sellTowerMenuSprite selectedSprite:nil target:self selector:@selector(sellTowerObjectAnimation)];
    CCMenu *sellTowerMenu = [CCMenu menuWithItems:sellTowerMenuItemSprite, nil];
    sellTowerMenu.position = ccp(-50, -50);
    
    [optionMenu addChild:upgradeTowerMenu];
    [optionMenu addChild:sellTowerMenu];
    
    optionMenu.position = ccp(spriteBody.textureRect.size.width/2, spriteBody.textureRect.size.height/2);
    optionMenu.scale = 0;
    optionMenu.visible = NO;
    [spriteBody addChild:optionMenu z:100];
}

-(void)showOption {
    if(!isShowOptionMenu) {
        isShowOptionMenu = TRUE;
        optionMenu.visible = YES;
        [optionMenu runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.25f scale:1.0f], nil]];
        [range runAction:[CCScaleTo actionWithDuration:0.25 scale:maxRadiusFireTarget*2/range.contentSize.width]];
    } else {
        isShowOptionMenu = FALSE;
        [optionMenu runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.25f scale:0], [CCHide action], nil]];
        [range runAction:[CCScaleTo actionWithDuration:0.25 scale:0]];
    }
}

-(void)sellTowerObjectAnimation {
    isShowOptionMenu = FALSE;
    CCCallFunc *sellCastleFunc = [CCCallFunc actionWithTarget:self selector:@selector(sellTowerObjectCallback)];
    [optionMenu runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.2f scale:0.0f], sellCastleFunc, nil]];
}

-(void)sellTowerObjectCallback {
    [(PlayScreen *)handler sellTower:self];
}

-(void)upgradeTowerAnimation {
    isShowOptionMenu = FALSE;
    CCCallFunc *upgradeCastleFunc = [CCCallFunc actionWithTarget:self selector:@selector(upgradeTowerCallback)];
    [optionMenu runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.2f scale:0.0f], upgradeCastleFunc, nil]];
}

-(void)upgradeTowerCallback {
    //implement in sub tower class
}

-(void)findAndFireTarget {
    int indexOfEnemyNearestDes = -1;
    float distanceNearestDes = 100000.0f; //set default is radiusLockTarget

    for(int i = 0; i < handler.listGameObject.count; i++) {
        //check if it is a enemy
        if([[handler.listGameObject objectAtIndex:i]isKindOfClass:[Enemy class]]) {
            float distance = sqrtf(powf([[handler.listGameObject objectAtIndex:i] spriteBody].position.x - spriteBody.position.x, 2) + powf([[handler.listGameObject objectAtIndex:i] spriteBody].position.y - spriteBody.position.y, 2));

            //if it in radiusFireTarget
            if(distance <= maxRadiusFireTarget) {
                float distanceFromEnemyToRoadDes = [(Enemy *)[handler.listGameObject objectAtIndex:i] remainDistanceToDes];
        
                if(distanceFromEnemyToRoadDes <= distanceNearestDes) {
                    indexOfEnemyNearestDes = i;
                    distanceNearestDes = distanceFromEnemyToRoadDes;
                }
            }
        }
    }
    
    //if found
    if(indexOfEnemyNearestDes >= 0) {
        isShooting = YES;
        [self lockTarget:[handler.listGameObject objectAtIndex:indexOfEnemyNearestDes]];
        [self shootTargetAnimation];
    }
}

-(void)lockTarget:(GameObject *)_target {
    targetLocked = _target;
}

-(void)shootTargetAnimation {
    //implement in sub class
}

-(void)fireTarget {
    //implement in sub class
}

-(void)hitTargetOfBullet:(GameObject *)_bullet {
    //Degree HP of enemy
    //[_bullet.spriteBody removeFromParentAndCleanup:YES];
    //[handler removeGameObject:_bullet];
    
    if([((PlayScreen *)handler).listGameObject containsObject:targetLocked]){
        ((Enemy *) targetLocked).HP -= ((BulletObject*)_bullet).damage;
        [((Enemy *) targetLocked) animationHit]; //07/06/2012
        [((Enemy *) targetLocked) updateBloodMeter];
    }

    isShooting = NO;
}

-(void)update:(ccTime)_timeUpdate {
    if(!isShooting)
        [self findAndFireTarget];
}

-(void)dealloc {  
    [bullet.spriteBody removeFromParentAndCleanup:YES];
    [handler removeGameObject:bullet];
    
    [self stopAllActions];
    [self removeAllChildrenWithCleanup:YES];
    [self removeFromParentAndCleanup:YES];
    
    [super dealloc];
}

@end
